package app.itgungnir.compose.wan.business.main.home

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.NearMe
import androidx.compose.material.icons.outlined.Search
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import app.itgungnir.compose.wan.R
import app.itgungnir.compose.wan.widgets.*
import kotlin.math.abs

@Composable
fun HomeScreen(navController: NavController = rememberNavController()) {
    val viewModel = viewModel<HomeViewModel>()
    // UI
    val toolbarFlexibleHeight = 40.dp
    val toolbarFlexibleHeightPx = with(LocalDensity.current) { toolbarFlexibleHeight.roundToPx().toFloat() }
    val contentOverflowHeightPx = remember { mutableStateOf(0F) }
    val toolbarCollapseRatio = remember { mutableStateOf(0F) }
    val nestedScrollConnection = remember {
        object : NestedScrollConnection {
            override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
                val delta = available.y
                val newOffset = contentOverflowHeightPx.value + delta
                contentOverflowHeightPx.value = newOffset.coerceAtMost(0F)
                val ratio = newOffset * 1.0F / toolbarFlexibleHeightPx
                toolbarCollapseRatio.value = abs(ratio.coerceIn(-1F, 0F))
                return Offset.Zero
            }
        }
    }
    Scaffold(topBar = { HomeTopBar(toolbarCollapseRatio) }) {
        val bannerFlow = viewModel.bannerFlow.collectAsState(initial = null)
        val hotArticleList by viewModel.hotArticleFlow.collectAsState(initial = null)
        val articleData = viewModel.articleFlow.collectAsLazyPagingItems()
        val lazyListState = rememberLazyListState()
        WanPagingList(
            modifier = Modifier.nestedScroll(connection = nestedScrollConnection),
            lazyListState = lazyListState,
            onRefresh = {
                viewModel.getBannerList()
                viewModel.getHotArticles()
            },
            pagingItems = articleData
        ) {
            item(key = "Home_Banner") {
                val visibleState = lazyListState.isItemVisible(key = "Home_Banner")
                WanBanner(
                    modifier = Modifier.padding(top = 10.dp),
                    itemsState = bannerFlow,
                    visibleState = visibleState
                )
            }
            item {
                HomeToolBox(navController = navController)
            }
            hotArticleList?.takeIf { it.isNotEmpty() }?.let { articles ->
                items(articles) { article ->
                    HomeArticleItem(navController = navController, item = article, hot = true) {
                        when (it) {
                            true -> viewModel.uncollectArticle(articleId = article.id)
                            else -> viewModel.collectArticle(articleId = article.id)
                        }
                    }
                }
            }
            items(articleData) { article ->
                HomeArticleItem(navController = navController, item = article) {
                    when (it) {
                        true -> viewModel.uncollectArticle(articleId = article?.id)
                        else -> viewModel.collectArticle(articleId = article?.id)
                    }
                }
            }
        }
    }
}

@Composable
private fun HomeTopBar(collapseRatio: MutableState<Float>) {
    val ratio = collapseRatio.value
    val toolbarHeight = 95.dp - (40 * ratio).dp
    val topAlpha = when (ratio <= 0.5F) {
        true -> 1F - ratio / 0.5F
        else -> 0F
    }
    val bottomPaddingHorizontal = when (ratio <= 0.3F) {
        true -> (45 * (ratio / 0.3F)).dp
        else -> 45.dp
    }
    val bottomPaddingTop = 40.dp - (40 * ratio).dp
    Surface(elevation = 4.dp) {
        Column(modifier = Modifier.fillMaxWidth()) {
            WanStatusBar()
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(toolbarHeight)
                    .background(color = MaterialTheme.colors.primary)
                    .padding(vertical = 10.dp, horizontal = 15.dp)
            ) {
                Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                    Image(
                        modifier = Modifier.size(35.dp),
                        painter = painterResource(id = R.mipmap.ic_launcher_round),
                        contentDescription = ""
                    )
                    WanHeader(
                        modifier = Modifier.weight(1F),
                        content = "玩JetpackCompose",
                        color = MaterialTheme.colors.onPrimary.copy(alpha = topAlpha),
                        textAlign = TextAlign.Center
                    )
                    WanIconButton(
                        modifier = Modifier.size(35.dp),
                        icon = Icons.Filled.NearMe
                    ) {
                        // TODO
                    }
                }
                Row(
                    modifier = Modifier
                        .padding(
                            start = bottomPaddingHorizontal,
                            end = bottomPaddingHorizontal,
                            top = bottomPaddingTop
                        )
                        .fillMaxWidth()
                        .height(35.dp)
                        .clip(shape = RoundedCornerShape(18.dp))
                        .background(color = MaterialTheme.colors.background)
                        .clickable { } // TODO
                        .padding(horizontal = 10.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        imageVector = Icons.Outlined.Search,
                        tint = MaterialTheme.colors.primary,
                        contentDescription = ""
                    )
                    WanDescription(
                        content = "请输入要搜索的内容",
                        color = MaterialTheme.colors.onBackground.copy(alpha = 0.6F)
                    )
                }
            }
        }
    }
}
